java构建树,构建tree,组装树结构,通用算法,用到递归算法

算法1:利用数据结构,空间换取时间(组装时对初始数据顺序有要求)


import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class Mainin {

	static class Node {
		String code;
		String parentCode;

		List<Node> children;

		public Node() {
			super();
		}

		public Node(String code, String parentCode) {
			super();
			this.code = code;
			this.parentCode = parentCode;
		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public String getParentCode() {
			return parentCode;
		}

		public void setParentCode(String parentCode) {
			this.parentCode = parentCode;
		}

		public List<Node> getChildren() {
			return children;
		}

		public void setChildren(List<Node> children) {
			this.children = children;
		}

		public void addChildren(Node child) {
			if (children == null) {
				children = new ArrayList<Node>();
			}
			children.add(child);
		}
	}

	public static void main(String[] args) {
		List<Node> initList = initTreeData();
		Map<String, Node> root = new LinkedHashMap<String, Node>();
		for (Node item : initList) {
			Node parent = root.get(item.getParentCode());
			if (parent == null) {
				parent = new Node();
				root.put(item.getParentCode(), parent);
			}
			root.put(item.getCode(), item);
			parent.addChildren(item);
		}
		Node tree = root.get("0");
		System.out.println(GsonUtils.toJson(tree));
	}

	static List<Node> initTreeData() {
		List<Node> initList = new ArrayList<>();
		initList.add(new Node("001", "0"));
		initList.add(new Node("001001", "001"));
		initList.add(new Node("001002", "001"));
		initList.add(new Node("002", "0"));
		initList.add(new Node("002001", "002"));
		initList.add(new Node("002002", "002"));
		initList.add(new Node("002002001", "002002"));
		initList.add(new Node("002002002", "002002"));
		initList.add(new Node("003", "0"));
		initList.add(new Node("003001", "003"));
		initList.add(new Node("003002", "003"));
		initList.add(new Node("003002001", "003002"));
		initList.add(new Node("003002002", "003002"));
		initList.add(new Node("003002003", "003002"));
		initList.add(new Node("003002004", "003002"));
		initList.add(new Node("003002005", "003002"));
		initList.add(new Node("003002006", "003002"));
		initList.add(new Node("005", "0"));
		initList.add(new Node("005001", "005"));
		initList.add(new Node("005001002", "005001"));
		initList.add(new Node("005001002001", "005001002"));
		initList.add(new Node("005001002002", "005001002"));
		return initList;
	}

}

算法2:只有一个字段,需要自己算树结构 

请跟着main方法走,然后看代码注释。
package hesuangyan.com.testtree;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Mainin {

    static class Node {
        // 节点对象,没有按照规范封装,直接.属性即可
        String code;

        List<Node> children = new ArrayList<Node>();
        Map<String, Node> childMap = new LinkedHashMap<String, Node>();

        Node() {
            this.code = "000";
        }

        Node(String code) {
            this.code = code;
        }

        @Override
        public String toString() {
            StringBuilder str = new StringBuilder();
            return printSelf(this, str);
        }

        public String printSelf(Node n, StringBuilder str) {//输出树的json结构
            List<Node> list = n.children;
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Node node = list.get(i);
                    int childeSize = node.children.size();
                    String mark = "";
                    if (childeSize != 0) {
                        mark = ":";
                    }
                    str.append("{code:" + node.code + mark);
                    printSelf(node, str);
                    str.append("}");
                    if (i + 1 != list.size()) {
                        str.append(",");
                    }
                }
            }
            return str.toString();
        }
    }

    public static void main(String[] args) {
        Node node = new Node();//
        initTreeData(node);// 构建树前的初始化平铺数据,模拟数据库查询出的数据

        Map<String, Node> rMap = new LinkedHashMap<String, Node>();// 临时组织数据map

        for (Node thisN : node.children) {
            turnToMap(rMap, thisN);// 将平铺的数据,解析到map中,构建一颗逻辑树
        }

        Node root = new Node();// 结果树
        turnToList(rMap, root);// 递归解析map树,并放入root这个根节点中
        System.out.println(root);
        // root既是结果树
    }

    static void turnToMap(Map<String, Node> rMap, Node n) {
        String key = null;
        List<String> keyList = new ArrayList<String>();
        for (int i = 0; i < n.code.length() / 3; i++) {// 组装code的父级结构
            key = n.code.substring(0, 3 + (i * 3));
            keyList.add(key);
        }

        String thisKey = null;
        Node tmpNode = null;
        Map<String, Node> tmpMap = rMap;
        for (int i = 0; i < keyList.size(); i++) {
            thisKey = keyList.get(i);
            tmpNode = tmpMap.get(thisKey);
            if (i + 1 == keyList.size()) {
                tmpMap.put(n.code, n);// 如果是末级节点,则放入该节点
            } else {
                tmpMap = tmpNode.childMap;// 如果不是末级节点,则将该节点赋值给临时变量
            }
        }
    }

    static void turnToList(Map<String, Node> rMap, Node rn) {
        Set<Entry<String, Node>> eSet = rMap.entrySet();
        Iterator<Entry<String, Node>> mIt = eSet.iterator();
        while (mIt.hasNext()) {
            Entry<String, Node> entry = mIt.next();
            Node node = entry.getValue();
            rn.children.add(node);
            turnToList(node.childMap, node);
        }
    }

    static void initTreeData(Node node) {
        node.children.add(new Node("001"));
        node.children.add(new Node("001001"));
        node.children.add(new Node("001002"));
        node.children.add(new Node("002"));
        node.children.add(new Node("002001"));
        node.children.add(new Node("002002"));
        node.children.add(new Node("002002001"));
        node.children.add(new Node("002002002"));
        node.children.add(new Node("003"));
        node.children.add(new Node("003001"));
        node.children.add(new Node("003002"));
        node.children.add(new Node("003002001"));
        node.children.add(new Node("003002002"));
        node.children.add(new Node("003002003"));
        node.children.add(new Node("003002004"));
        node.children.add(new Node("003002005"));
        node.children.add(new Node("003002006"));

        node.children.add(new Node("005"));
        node.children.add(new Node("005001"));
        node.children.add(new Node("005001002"));
        node.children.add(new Node("005001002001"));
        node.children.add(new Node("005001002002"));
    }

}

 

 

 

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值